package main

import (
	"flag"
	"fmt"
	"go_final/mxshop_srvs/userop_srv/global"
	"go_final/mxshop_srvs/userop_srv/handler"
	"go_final/mxshop_srvs/userop_srv/initialize"
	addresspb "go_final/mxshop_srvs/userop_srv/proto/protofile/address"
	messagepb "go_final/mxshop_srvs/userop_srv/proto/protofile/message"
	user_favpb "go_final/mxshop_srvs/userop_srv/proto/protofile/user_fav"
	"go_final/mxshop_srvs/userop_srv/utils"
	"go_final/mxshop_srvs/userop_srv/utils/register/consul"
	"net"
	"os"
	"os/signal"
	"syscall"

	"go.uber.org/zap"

	uuid "github.com/satori/go.uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
)

func main() {
	// 2.初始化logger
	initialize.InitLogger()

	// 1.初始化配置文件
	initialize.InitConfig()

	// 3.初始化数据库
	initialize.InitDB()

	IP := flag.String("ip", "0.0.0.0", "ip地址")
	Port := flag.Int("port", 50051, "端口号")
	flag.Parse()
	if *Port == 0 {
		var err error
		*Port, err = utils.GetFreePort()
		if err != nil {
			// 没有找到可用端口
			panic(err)
		}
	}
	zap.S().Info("*Port ", *Port)

	s := grpc.NewServer()

	// 多次注册服务
	messagepb.RegisterMessageServer(s, &handler.MessageServer{})
	addresspb.RegisterAddressServer(s, &handler.AddressServer{})
	user_favpb.RegisterUserFavServer(s, &handler.UserFavServer{})

	lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", *IP, *Port))
	if err != nil {
		panic(err)
	}

	go func() {
		err = s.Serve(lis)
		if err != nil {
			panic(err)
		}
	}()

	// 注册服务健康检查(这一行为grpc健康检查特有代码, 不可省略, 否则健康检查会不通过)
	grpc_health_v1.RegisterHealthServer(s, health.NewServer())

	// 5.服务注册
	registerClient := consul.NewRegistry(global.ServerConfig.ConsulInfo.Host, global.ServerConfig.ConsulInfo.Port)
	serviceID := fmt.Sprintf("%s", uuid.NewV4())
	err = registerClient.Register("192.168.4.170", *Port, global.ServerConfig.Name,
		global.ServerConfig.Tags,
		serviceID)
	if err != nil {
		zap.S().Panic("服务注册失败", err.Error())
	}

	// 接收终止信号
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	<-quit
	if err = registerClient.DeRegister(serviceID); err != nil {
		zap.S().Info("注销服务失败", err)
	} else {
		zap.S().Info("注销服务成功")
	}
}
